//
//  MarketTypeViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/9.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "MarketTypeViewController.h"
#import "MarketGoodsCell.h"
#import "GoodDetailViewController.h"
#import "AF_MainScreeningViewController.h"

@interface MarketTypeViewController () <UITableViewDelegate, UITableViewDataSource, MarketGoodCellDelegate>

@property (weak, nonatomic) IBOutlet UIView *topbar;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) UIButton *button1;
@property (strong, nonatomic) UIButton *button2;
@property (strong, nonatomic) UIButton *button3;
@property (assign, nonatomic) BOOL clickHot;
@property (assign, nonatomic) BOOL clickSell;
@property (assign, nonatomic) BOOL clickPrice;

@property (strong, nonatomic) NSMutableArray *searchResult;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) NSString *sortType;
@property (strong, nonatomic) NSString *sortby;

@property (assign, nonatomic) BOOL pageToEnd;

@end

@implementation MarketTypeViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:POST_STARTSX object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self makeTopBar];
    UIView *blankView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    self.tableView.tableFooterView = blankView;
    [self addLoadMoreFooter:self.tableView];

    self.pageToEnd = NO;
    self.page = 1;
    self.clickHot = NO;
    self.clickSell = NO;
    self.clickPrice = NO;
    self.sortType = @"0";
    self.sortby = @"0";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sxSearch:) name:POST_STARTSX object:nil];
    
    [[DataCenter sharedDataCenter] resetSXData];
    [self loadNetworkData];
}

- (void)sxSearch:(NSNotification *)notify {
    self.page = 1;
    self.pageToEnd = NO;
    [self loadNetworkData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)goPop {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:self.marketTypeName];
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
}

- (void)makeTopBar {
    self.button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button1.frame = CGRectMake(0, 0, ScreenWidth / 6, 50);
    [self.button1 setTitle:@"最热" forState:UIControlStateNormal];
    self.button1.titleLabel.font = [UIFont systemFontOfSize:15];
    self.button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button1 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
    [self.button1 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.button1 setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 0)];
    
    self.button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button2.frame = CGRectMake(ScreenWidth / 6, 0, ScreenWidth / 6, 50);
    [self.button2 setTitle:@"销量" forState:UIControlStateNormal];
    self.button2.titleLabel.font = [UIFont systemFontOfSize:15];
    self.button2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button2 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
    [self.button2 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.button2 setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 0)];
    
    self.button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button3.frame = CGRectMake(ScreenWidth / 3, 0, ScreenWidth / 6, 50);
    [self.button3 setTitle:@"价格" forState:UIControlStateNormal];
    self.button3.titleLabel.font = [UIFont systemFontOfSize:15];
    self.button3.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.button3 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
    [self.button3 setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.button3 setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 0)];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake(ScreenWidth - 15 - 80, 0, 80, 50);
    [button3 setTitle:@"筛选" forState:UIControlStateNormal];
    button3.titleLabel.font = [UIFont systemFontOfSize:15];
    button3.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.topbar addSubview:self.button1];
    [self.topbar addSubview:self.button2];
    [self.topbar addSubview:self.button3];
    [self.topbar addSubview:button3];
    
    [self.button1 addTarget:self action:@selector(clickHot:) forControlEvents:UIControlEventTouchUpInside];
    [self.button2 addTarget:self action:@selector(clickSell:) forControlEvents:UIControlEventTouchUpInside];
    [self.button3 addTarget:self action:@selector(clickPrice:) forControlEvents:UIControlEventTouchUpInside];
    [button3 addTarget:self action:@selector(clickSuai:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)loadNetworkData {
    self.page = 1;
    self.pageToEnd = NO;
    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *url = [NSString stringWithFormat:@"%@/product/productList?page=%ld&sortby=%@&sortType=%@&goods_kind=%ld&goods_name=%@&startPrice=%@&endPrice=%@&goods_sell_type=%@", APIYIGOU, self.page, self.sortby, self.sortType, self.marketTypeid, [DataCenter sharedDataCenter].sxname, [DataCenter sharedDataCenter].sxprice1, [DataCenter sharedDataCenter].sxprice2, [DataCenter sharedDataCenter].sxtype];
    NSString *url = [NSString stringWithFormat:@"%@/product/productList?page=%ld&sortby=%@&goods_kind=%@", APIYIGOU, self.page, self.sortby, self.marketTypeid];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [JSONModel addDatasFromDict:[dict objectForKey:@"data"] withModel:@"MMMarketNew" forKey:@"list" target:self.searchResult isAppend:NO];
        [ViewFactory dismissLoading];
        [self.tableView reloadData];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"查询失败！"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}

- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [self.tableView.footer endRefreshing];
        return;
    }
    
//    if (!self.marketTypeName) {
//        self.marketTypeName = @"";
//    }
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/productList?page=%ld&sortby=%@&sortType=%@&goods_kind=%@&goods_name=%@&startPrice=%@&endPrice=%@&goods_sell_type=%@", APIYIGOU, self.page, self.sortby, self.sortType, self.marketTypeid, [DataCenter sharedDataCenter].sxname, [DataCenter sharedDataCenter].sxprice1, [DataCenter sharedDataCenter].sxprice2, [DataCenter sharedDataCenter].sxtype];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [[dict objectForKey:@"data"] objectForKey:@"list"];
        if (array.count == 0) {
            self.pageToEnd = YES;
        }
        [JSONModel addDatasFromDict:[dict objectForKey:@"data"] withModel:@"MMMarketNew" forKey:@"list" target:self.searchResult isAppend:YES];
        [ViewFactory dismissLoading];
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (self.searchResult.count / 2 + self.searchResult.count % 2);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 307 - 50 - 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MarketGoodsCell *cell = GET_CELL(MarketGoodsCell, @"MarketGoodsCell");
    cell.titleH.constant = 0;
    cell.lineH.constant = 0;
    cell.title.hidden = YES;
    cell.line.hidden = YES;
    
    MMMarketNew *ldata = nil;
    MMMarketNew *rdata = nil;
    if (self.searchResult.count > indexPath.row * 2) {
        ldata = [self.searchResult objectAtIndex:(indexPath.row * 2)];
    }
    if (self.searchResult.count > indexPath.row * 2 + 1) {
        rdata = [self.searchResult objectAtIndex:(indexPath.row * 2 + 1)];
    }
    
    cell.type = IMarketGoodCellNew;
    cell.index = indexPath.row;
    cell.delegate = self;
    [cell fillWithData:ldata right:rdata];
    return cell;
}

- (void)clickMarketGoodCell:(NSInteger)index isLeft:(BOOL)clickLeft myType:(MarketGoodCellType)type {
    MMMarketNew *gooddata = nil;
    if (clickLeft) {
        gooddata = [self.searchResult objectAtIndex:index * 2];
    } else {
        gooddata = [self.searchResult objectAtIndex:(index * 2 + 1)];
    }
    
    if (gooddata) {
        [[GoToManager sharedGoToManager] go:self type:ToGoodDetail data:gooddata];
    }
}

- (void)clickHot:(UIButton *)button {
    self.clickHot = !self.clickHot;
    [self refreshArrow:self.clickHot];
    self.sortType = @"0";
    [self loadNetworkData];
}

- (void)clickSell:(UIButton *)button {
    self.clickSell = !self.clickSell;
    [self refreshArrow:self.clickSell];
    self.sortType = @"1";
    [self loadNetworkData];
}

- (void)clickPrice:(UIButton *)button {
    self.clickPrice = !self.clickPrice;
    [self refreshArrow:self.clickPrice];
    self.sortType = @"2";
    [self loadNetworkData];
}

- (void)clickSuai:(UIButton *)button {
    AF_MainScreeningViewController * testVC = [AF_MainScreeningViewController new];
    //这两句必须有
    self.definesPresentationContext = YES; //self is presenting view controller
    testVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    /** 设置半透明度 */
    testVC.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
    
    [self presentViewController:testVC animated:NO completion:nil];
}

- (void)refreshArrow:(BOOL)sort {
    if (sort) {
        self.sortby = @"1";
    } else {
        self.sortby = @"0";
    }
    
    if (self.clickHot)
        [self.button1 setImage:[UIImage imageNamed:@"uparrow"] forState:UIControlStateNormal];
    else
        [self.button1 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
    if (self.clickSell)
        [self.button2 setImage:[UIImage imageNamed:@"uparrow"] forState:UIControlStateNormal];
    else
        [self.button2 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
    if (self.clickPrice)
        [self.button3 setImage:[UIImage imageNamed:@"uparrow"] forState:UIControlStateNormal];
    else
        [self.button3 setImage:[UIImage imageNamed:@"downarrow"] forState:UIControlStateNormal];
}

ARRAY_INIT(searchResult)

@end
